package com.example.project.service;

import com.example.project.dto.CarItem;
import com.example.project.mapper.ShopcarMapper;
import com.example.project.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Lenovo
 * @version 1.0
 * @date 2025/5/7 16:53
 * @className ShopcarService
 */
@Service
public class ShopcarService {
    @Autowired
    private ShopcarMapper shopcarMapper;
    @Autowired
    private UserMapper userMapper;

    //1. 添加到购物车
    public boolean addCar(int userid,int goodid,int num) {
        //1.1. 判断购物车是否有该商品
        int gooditemid = this.getGoodItemIdBygoodId(userid,goodid);
        if(gooditemid != -1){
            //数量追加
            shopcarMapper.appendNum(num,userid,goodid);
            return true;
        }else{
            //1.3. 如果没有则，正常添加
            boolean isAdd = this.addGoodItem(userid,goodid,num);
            if(isAdd){
                //找到最新的商品项id
                int newgooditemid = this.getGoodItemId(userid,goodid);
                //加入到购物车中
                return shopcarMapper.addCar(userid,newgooditemid) > 0;
            }
        }

        return  false;
    }
    //2. 添加购物车商品项
    public boolean addGoodItem(int userid,int goodid,int num){
        return shopcarMapper.addGoodItem(userid,goodid,num) >0;
    }
    //3. 获取gooditemid
    public int getGoodItemId(int userid,int goodid){
        return shopcarMapper.getGoodItemId(userid,goodid);
    }
    //4. 获取购物车数据
    public List<CarItem> getCar(int userid){
        return shopcarMapper.getCar(userid);
    }

    //5.判断购物车是否有商品，如果有则返回gooditemid
    public Integer getGoodItemIdBygoodId(int userid,int goodid){
        System.out.println(userid+" "+goodid);
        Integer gooditemid = shopcarMapper.getGoodItemIdBygoodId(userid,goodid);
        if(gooditemid ==null){
            return -1;
        }else{
            return gooditemid;
        }
    }
    //6.修改某个商品的数量


    //返回总价格
    public Double getTotalPrice(int userid) {
        List<CarItem> car = this.getCar(userid);
        Double totalPrice = 0.0;
        //遍历计算价格
        for (CarItem carItem : car) {
            totalPrice += carItem.getGoodprice() * carItem.getNum();
        }
        return totalPrice;
    }
    //清理购物车
    public void clearCar(Integer userId) {
        shopcarMapper.clearCar(userId);
        shopcarMapper.clearCarItem(userId);
    }
}
